<template>
  <div class="game-page">
    <!-- iframe 区域 -->
    <div class="game-iframe-container" >
      <iframe
          v-if="iframeUrl"
          :src="iframeUrl"
          frameborder="0"
          scrolling="no"
          @load="onIframeLoad"
      ></iframe>
      <div v-else class="loading-placeholder">
        <el-skeleton :rows="10" animated />
      </div>
    </div>

    <!-- URL 显示区域 -->
    <div class="url-display-container">
      <div class="url-content">
        <span class="url-label">游戏链接：</span>
        <template v-if="showUrlDisplay">
          <el-input
              v-model="iframeUrl"
              readonly
              class="url-input"
              @click="copyUrl"
          />
        </template>
        <el-button
            type="primary"
            class="toggle-url-btn"
            @click="handleShowUrl"
            :icon="showUrlDisplay ? 'Hide' : 'View'"
        >
          {{ showUrlDisplay ? '隐藏链接' : '显示链接' }}
        </el-button>
      </div>
    </div>

    <!-- 公告弹窗 -->
    <el-dialog
        v-model="showAnnouncement"
        :title="`游戏公告 - ${currentAnnouncement?.date || ''}`"
        width="50%"
        :before-close="handleCloseAnnouncement"
    >
      <div class="announcement-content" v-if="currentAnnouncement">
        <!-- 公告内容 -->
        <h3>{{ currentAnnouncement.title }}</h3>
        <div v-for="(item, index) in currentAnnouncement.content" :key="index">
          <p v-if="!item.startsWith('1.') && !item.startsWith('2.')">{{ item }}</p>
          <h4 v-else>{{ item }}</h4>
        </div>
        <p class="announcement-date">{{ currentAnnouncement.date }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleCloseAnnouncement">我知道了</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Search, Plus, CaretTop, DocumentCopy, View, Hide } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { typeList } from '@/data/spirit-types'
import { getSpiritList } from '@/api/spirit'
import { useUserStore } from '@/stores/user'
import { getGameSession } from '@/api/game'

const iframeUrl = ref('')


// 控制公告显示状态
const showAnnouncement = ref(false)
const currentAnnouncement = ref(null)

// 添加控制 URL 显示的状态
const showUrlDisplay = ref(false)

// 添加标记变量
const hasShownLoadMessage = ref(false)



// 总数量
const total = ref(0)


// 添加公告数据的 ref
const latestAnnouncement = ref(null);

onMounted(async () => {
  try {

    // // 从CDN获取公告数据
    // await fetchAnnouncementsFromCDN()
    // // 从localStorage获取isRead状态
    // const isRead = localStorage.getItem('isRead')
    // // 如果isRead为true，则显示公告
    // if (isRead === 'true') {
    //   // 获取最新的公告
    //   currentAnnouncement.value = JSON.parse(localStorage.getItem('announcement'))
    //   showAnnouncement.value = true
    // }else{
    //   // 获取游戏会话
    //   const res = await getGameSession()
    //   if (res.code === 200) {
    //     let new_session = res.session
    //     localStorage.setItem('seer_session', new_session)
    //   }
    // }
      // 获取游戏会话
      const res = await getGameSession()
      if (res.code === 200) {
        let new_session = res.session
        localStorage.setItem('seer_session', new_session)
      }

    // 检查用户是否登录
    const session = localStorage.getItem('seer_session')
    if (!session) {
      ElMessage.warning('请先登录')
      return
    }

    // 设置游戏 iframe 的 URL
    iframeUrl.value = `${import.meta.env.VITE_GAME_URL}/?sid=${session}&t=${Math.floor(Date.now() / 1000)}`

    // 获取用户信息
    // const userInfo = await userStore.fetchUserInfo()
    // if (!userInfo) {
    //   console.warn('获取用户信息失败，继续加载游戏内容')
    // }

  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('页面初始化失败，请刷新重试')
  }
})

// 添加获取公告的函数
const fetchAnnouncementsFromCDN = async () => {
  try {
    const response = await fetch('http://yd.sjcmc.cn:16578/announcements.json');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const jsonData = await response.json();
    // 获取最新的公告（第一条）
    if (jsonData.announcements && jsonData.announcements.length > 0) {
      const oldannouncement = localStorage.getItem('announcement')
      if (oldannouncement && JSON.parse(oldannouncement).date !== jsonData.announcements[0].date) {
        localStorage.setItem('isRead', 'true')
      }
      const announcement = jsonData.announcements[0];
      localStorage.setItem('announcement', JSON.stringify(announcement));
    }
  } catch (error) {
    console.error('获取公告数据失败:', error);
  }
};

const onIframeLoad = () => {
  // 只在第一次显示消息
  if (!hasShownLoadMessage.value && iframeUrl.value) {
    ElMessage.success('游戏加载成功')
    hasShownLoadMessage.value = true
  }
}




// 复制 URL 的方法
const copyUrl = async () => {
  try {
    // 首先尝试使用 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(iframeUrl.value)
      ElMessage.success('链接已复制到剪贴板')
      return
    }

    // 后备方案：创建临时文本区域
    const textArea = document.createElement('textarea')
    textArea.value = iframeUrl.value
    textArea.style.position = 'fixed'
    textArea.style.left = '-9999px'
    textArea.style.top = '-9999px'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    try {
      document.execCommand('copy')
      ElMessage.success('链接已复制到剪贴板')
    } catch (err) {
      console.error('复制失败:', err)
      ElMessage.error('复制失败，请手动复制')
    } finally {
      document.body.removeChild(textArea)
    }
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 处理关闭公告
const handleCloseAnnouncement = () => {
  // 关闭公告并设置localStorage
  showAnnouncement.value = false
  localStorage.setItem('isRead', 'false')
}

// 处理显示 URL 的方法
const handleShowUrl = () => {
  showUrlDisplay.value = !showUrlDisplay.value
  if (showUrlDisplay.value) {
    ElMessage.warning('此链接相当于密码，请勿转发给其他人')
  }
}

// TODO 通过精灵名称打开外链的精灵图鉴
const openNewSpiritDetail = (spiritName)=> {
  window.open('https://seer.fandom.com/zh/wiki/'+spiritName, '_blank');
  // window.open('https://wiki.biligame.com/seer/'+spiritName, '_blank');
}
</script>

<style lang="scss" scoped>
/* IE 兼容性样式 */
:global(html), :global(body) {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
  /* IE10+ 滚动条样式 */
  -ms-overflow-style: -ms-autohiding-scrollbar;
}

:global(#app) {
  height: 100%;
  /* IE Flex 布局兼容 */
  display: -ms-flexbox;
  display: flex;
}

.game-page {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  background-color: var(--el-bg-color-page);
  /* IE Flex 布局兼容 */
  display: -ms-flexbox;
  display: flex;
  -ms-flex-direction: column;
  flex-direction: column;
  -ms-flex-align: center;
  align-items: center;
  gap: 20px;
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
  /* IE 滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: var(--el-color-primary) var(--el-bg-color-page);

  /* 现代浏览器滚动条样式 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: var(--el-text-color-secondary);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: var(--el-bg-color-page);
  }

  /* IE10+ Gap 兼容 */
  & > * {
    margin-bottom: 20px;
  }

  & > *:last-child {
    margin-bottom: 0;
  }
}

.game-iframe-container {
  width: 1000px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
  position: relative;
}

iframe {
  width: 100%;
  height: 600px;
  border: none;
  margin-bottom: 10px;
  display: block;
}

.flash-tip {
  color: #666;
  font-size: 14px;
}

.spirit-type-section {
  width: 1000px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.search-area {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.spirit-search {
  width: 300px;
}

.type-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.type-item {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: #f5f7fa;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.type-item:hover {
  background: #ecf5ff;
  transform: translateY(-2px);
}

.type-item.active {
  background: #409eff;
  color: white;
}

.type-icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}

.spirit-showcase {
  width: 1000px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.spirit-grid {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 1fr 12px 1fr 12px 1fr 12px 1fr 12px 1fr 12px 1fr 12px 1fr 12px 1fr;
  grid-template-columns: repeat(8, 1fr);
  gap: 12px;
  margin-bottom: 20px;
  box-sizing: border-box;
}

.spirit-card {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  box-sizing: border-box;
}

.spirit-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.spirit-image {
  width: 100%;
  height: 0;
  padding-bottom: 100%;  /* 保持正方形容器 */
  background: #fff;
  border-radius: 4px;
  position: relative;
  margin-bottom: 6px;
  overflow: hidden;
  box-sizing: border-box;
}

.spirit-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;  /* 使用 contain 保持原始比例 */
  display: block;
  transition: transform 0.3s ease;
}

/* 修改悬停效果 */
.spirit-card:hover .spirit-image img {
  transform: scale(1.1);  /* 简化 transform */
}

.spirit-name {
  font-size: 12px;
  color: #333;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.load-more {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  margin-bottom: 30px;
}

.load-more-btn {
  width: 240px;
  height: 44px;
  font-size: 15px;
  border-radius: 22px;
  transition: all 0.3s ease;
}

.load-more-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.load-more-btn .el-icon {
  margin-right: 8px;
  font-size: 18px;
  transition: all 0.3s ease;
}

.load-more-btn .is-loading {
  animation: rotating 2s linear infinite;
}

.load-more-btn .button-text {
  vertical-align: middle;
}

@keyframes rotating {
  from {
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -ms-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

/* 添加波纹效果 */
.load-more-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 120%;
  height: 120%;
  border-radius: 50%;
  background: rgba(64, 158, 255, 0.1);
  -ms-transform: translate(-50%, -50%) scale(0);
  transform: translate(-50%, -50%) scale(0);
  opacity: 0;
  -ms-transition: all 0.5s;
  transition: all 0.5s;
}

.load-more-btn:active::after {
  transform: translate(-50%, -50%) scale(1);
  opacity: 1;
}

/* 添加回到顶部按钮样式 */
.back-to-top {
  :deep(.el-backtop) {
    background-color: #fff;  // 改为白色背景
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    z-index: 999;
    width: 50px;
    height: 50px;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.3);

    &:hover {
      transform: translateY(-5px);
      background-color: #f5f7fa;  // 悬停时背景色变浅
      box-shadow: 0 5px 15px rgba(64, 158, 255, 0.5);
    }
  }

  .back-to-top-content {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-icon {
      font-size: 24px;
      color: #409EFF;  // 图标改为蓝色
    }
  }
}

.url-display-container {
  width: 1000px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;

  .url-content {
    display: flex;
    align-items: center;
    gap: 12px;

    .url-label {
      font-size: 15px;
      font-weight: 500;
      color: #333;
      white-space: nowrap;
    }

    .url-input {
      flex: 1; // 让输入框占据剩余空间
      animation: fadeIn 0.3s ease;

      :deep(.el-input__wrapper) {
        background-color: #f5f7fa;
        box-shadow: none !important;
        border: 1px solid #e4e7ed;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--el-color-primary);
          background-color: #ecf5ff;
        }
      }

      :deep(.el-input__inner) {
        color: #606266;
        cursor: pointer;
        user-select: all;
      }
    }

    .toggle-url-btn {
      white-space: nowrap;
      min-width: 100px;
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.announcement-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 10px;
}

.announcement-content h3 {
  color: #409EFF;
  text-align: center;
  margin-bottom: 20px;
}

.announcement-content ul {
  margin: 15px 0;
  padding-left: 20px;
}

.announcement-content ul li {
  margin-bottom: 8px;
}

.announcement-date {
  text-align: right;
  color: #909399;
  margin-top: 20px;
  font-style: italic;
}
</style>